# -*- coding: utf-8 -*-
"""
Created on Thu Apr 15 14:24:27 2021

@author: HisenTsai
"""

import pyaudio
import wave
import numpy as np
import os

from scipy import signal
import matplotlib.pyplot as plt
import scipy.io.wavfile


def Monitor():
    CHUNK = 512
    FORMAT = pyaudio.paInt16
    CHANNELS = 1
    RATE = 48000
    #TEMP_OUTPUT_FILENAME = "temp.wav"
    WAVE_OUTPUT_FILENAME = "cache.wav"
    
    while(True): 
        #判断识别过程
        tempB = 1
        while (True):
            
            #如果文件存在
            if os.path.exists(WAVE_OUTPUT_FILENAME):
                if tempB==1:
                    print('识别中请稍后')
                    tempB = 0;
            else:
                break;
        
        
        
        
        p = pyaudio.PyAudio()
        stream = p.open(format=FORMAT,
                        channels=CHANNELS,
                        rate=RATE,
                        input=True,
                        frames_per_buffer=CHUNK)
        print("开始缓存录音")
        frames = []
        breakBoot = False
        start = 0
        index = 0
        while (True):
            
            print('begin ')
            #读取一小段声音
            for i in range(0, 50):
                data = stream.read(CHUNK)
                frames.append(data)
            audio_data = np.frombuffer(data, dtype=np.short)
            #获取其中大于指定的声音段数
            #large_sample_count = np.sum( audio_data > 600 )
            temp = np.max(audio_data)
            temp2 = np.min(audio_data)
            
            start += i
            if temp > 800 and breakBoot == False:
                index = start - i
                #表示可以检测声音停止了
                breakBoot = True
                print ("检测到信号,最小值", temp2)
                print ('当前阈值：',temp )
            elif breakBoot and temp < 300:  
                #a = int((start - index ) / 2)
                a = index - 50
                frames = frames[a:]
                
                if(len(frames) < 100):
                    print ('音频长度不合格：',len(frames))
                    frames = []
                    index = 0
                    start = 0
                    breakBoot = False
                else:
                    break
            
        #写入
        stream.stop_stream()
        stream.close()
        p.terminate()
        wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
        wf.setnchannels(CHANNELS)
        wf.setsampwidth(p.get_sample_size(FORMAT))
        wf.setframerate(RATE)
        wf.writeframes(b''.join(frames))
        wf.close()
        
        #示图
        sample_rate, s = scipy.io.wavfile.read(WAVE_OUTPUT_FILENAME)
        #进行短时傅里叶变换
        f, t, Zxx = signal.stft(s, fs=sample_rate,window='hann',nperseg=256,noverlap=None,nfft=None,
        detrend=False,return_onesided=True,boundary='zeros',padded=True,axis=-1)
        
        Z = np.log(np.abs(Zxx))
        
        plt.figure(figsize=(20,10))
        plt.subplot(2,1,1)
        plt.plot(np.arange(len(s))/sample_rate, s)
        plt.xlim([0, len(s)/sample_rate])
        plt.subplot(2,1,2)
        plt.pcolormesh(t, f, Z)
        plt.title('STFT Magnitude')
        plt.ylabel('Frequency [Hz]')
        plt.xlabel('Time [sec]')
        plt.show()
        
        

if __name__ == '__main__':
    Monitor()